import 'dart:io';

import 'package:emotion_keyboard/chat_type.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

import 'chat_input_bar.dart';
import 'chat_model.dart';
import 'chat_viewmodel.dart';

class ChatPage extends StatefulWidget {
  const ChatPage({Key? key}) : super(key: key);

  @override
  _ChatPageState createState() => _ChatPageState();
}

class _ChatPageState extends State<ChatPage> with WidgetsBindingObserver {
  final ScrollController _scrollController = ScrollController();
  final GlobalKey<ChatInputBarState> _chatInputBarKey = GlobalKey();
  final List<ChatModel> _models = [];
  bool _isLoading = false;

  @override
  void initState() {
    super.initState();

    _models.addAll(ChatViewModel.models);

    _scrollController.addListener(() {
      var maxScrollExtent = _scrollController.position.maxScrollExtent;
      var pixels = _scrollController.position.pixels;
      var dis = maxScrollExtent - pixels;

      //下拉加载更多
      if (dis <= 0) {
        _loadData();
      }
    });
  }

  Future<void> _loadData() async {
    if (_isLoading) return;

    setState(() {
      _isLoading = true;
    });

    Future.delayed(const Duration(milliseconds: 1000), () {
      setState(() {
        for (var i = 0; i < 3; i++) {
          _models.add(ChatModel.fromJson({
            "name": "小四",
            "chatStr":
                "[爱心]https://www.baidu.com/[傲慢]林萌喜欢小四,https://www.baidu.com/",
          }));
        }
        _isLoading = false;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.green,
      //键盘弹出页面不会上移 禁止页面上移
      resizeToAvoidBottomInset: false,
      appBar: AppBar(
        title: const Text("聊天界面"),
      ),
      body: Container(
        color: Colors.green,
        width: double.infinity,
        height: double.infinity,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            _buildListView(),
            _buildInputBar(),
          ],
        ),
      ),
    );
  }

  _buildListView() {
    return Expanded(
        child: GestureDetector(
      behavior: HitTestBehavior.opaque,
      onPanDown: (_) {
        _chatInputBarKey.currentState!.hidenKeyBoard();
      },
      child: Container(
        alignment: Alignment.topCenter,
        child: ListView.builder(
            padding: const EdgeInsets.only(top: 15),
            //让内容反转，滚动到最下面
            reverse: true,
            shrinkWrap: true,
            controller: _scrollController,
            itemCount: _models.length + 1,
            itemBuilder: (ctx, index) {
              if (index == _models.length) {
                return Visibility(
                    visible: _isLoading,
                    child: const CupertinoActivityIndicator(
                      radius: 10,
                    ));
              } else {
                if (_models[index].name == "刘亦菲") {
                  return _buildLeftContent(_models[index]);
                }
                return _builRightContent(_models[index]);
              }
            }),
      ),
    ));
  }

  _buildLeftContent(ChatModel model) {
    return Container(
      padding: const EdgeInsets.fromLTRB(15, 5, 15, 10),
      alignment: Alignment.center,
      child: Column(
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Image.asset(
                "lib/images/default_head.png",
                width: 35,
                height: 35,
              ),
              Flexible(
                  child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Container(
                      padding: const EdgeInsets.only(
                        left: 10,
                      ),
                      child: Text(model.name!,
                          style: const TextStyle(color: Colors.white))),
                  Container(
                    constraints: const BoxConstraints(
                      maxWidth: 300,
                    ),
                    margin: const EdgeInsets.only(top: 10, left: 10, right: 45),
                    padding: const EdgeInsets.fromLTRB(10, 6, 10, 8),
                    decoration: const BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.only(
                        topRight: Radius.circular(18),
                        bottomLeft: Radius.circular(15),
                        bottomRight: Radius.circular(15),
                      ),
                    ),
                    child: GestureDetector(
                      onTap: () {
                        print('点击');
                      },
                      onLongPress: () {
                        print("长按");
                      },
                      child: ChatViewModel.getRichText(model.chatStr!),
                    ),
                  )
                ],
              ))
            ],
          ),
        ],
      ),
    );
  }

  _builRightContent(ChatModel model) {
    return Container(
      padding: const EdgeInsets.fromLTRB(15, 5, 15, 10),
      alignment: Alignment.center,
      child: Column(
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.end,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Flexible(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.end,
                  children: [
                    Container(
                      padding: const EdgeInsets.only(
                        right: 15,
                      ),
                      child: Text(model.name!,
                          style: const TextStyle(color: Colors.white)),
                    ),
                    Container(
                      constraints: const BoxConstraints(
                        maxWidth: 300,
                      ),
                      margin:
                          const EdgeInsets.only(top: 10, right: 10, left: 45),
                      padding: const EdgeInsets.fromLTRB(10, 6, 10, 8),
                      decoration: BoxDecoration(
                        color: model.type == ChatContentType.text
                            ? Colors.white
                            : null,
                        borderRadius: const BorderRadius.only(
                          topLeft: Radius.circular(15),
                          bottomLeft: Radius.circular(15),
                          bottomRight: Radius.circular(18),
                        ),
                      ),
                      child: GestureDetector(
                        onTap: () {
                          print('点击');
                        },
                        onLongPress: () {
                          print("长按");
                        },
                        // child: ChatViewModel.getRichText(model.chatStr!),
                        child: _getChatContent(model),
                      ),
                    )
                  ],
                ),
              ),
              Image.asset(
                "lib/images/default_head.png",
                width: 35,
                height: 35,
              )
            ],
          ),
        ],
      ),
    );
  }

  _getChatContent(ChatModel model) {
    if (model.type == ChatContentType.text) {
      return ChatViewModel.getRichText(model.chatStr!);
    } else {
      return Container(
        constraints: const BoxConstraints(maxHeight: 150, maxWidth: 150),
        child: Image.file(File(model.chatStr!)),
        decoration: BoxDecoration(
            color: Colors.red, borderRadius: BorderRadius.circular(50)),
      );
    }
  }

  _buildInputBar() {
    return ChatInputBar(
      key: _chatInputBarKey,
      textHandle: (String text) {
        ChatModel model = ChatModel(
          name: "小四",
          chatStr: text,
        );
        setState(() {
          _models.insert(0, model);
        });
        _scrollController.animateTo(0.0,
            duration: const Duration(milliseconds: 200), curve: Curves.linear);
      },
      photoHandle: (String path) {
        //传给服务器的是base64字符串
        ChatModel model =
            ChatModel(name: "小四", chatStr: path, type: ChatContentType.photo);
        print("照片路径$path");
        setState(() {
          _models.insert(0, model);
        });
        _scrollController.animateTo(0.0,
            duration: const Duration(milliseconds: 200), curve: Curves.linear);
      },
    );
  }
}
